<template>
  <div class="home">
    <div class="title">
      <p class="nav-title">首页</p>
    </div>
    <!-- 级联选择 -->
    <van-cell class="van-cell" title="当前网点选择" is-link :value="currentwd" @click="toSelect"/>
    <!-- 级联选择弹出框 -->
    <van-popup v-model="show" position="bottom" :style="{ height: '40%'}">
      <van-tree-select
          height="55vw"
          :items="orgList"
          :main-active-index="activeid"
          :active-id="activeid2"
          @click-nav="onNavClick">
        <template #content>
          <div v-for='(item, index) in roomList' :key="index">
            <van-cell :class="{active:activeid2==item.id}" :value="item.text"
                      @click="onItemClick(item.text, item.id)"></van-cell>
          </div>
        </template>
      </van-tree-select>
      <van-button class="selectbtn" type="info" @click="onRoomSelect">完成</van-button>
    </van-popup>


    <!-- 告警处理弹出框 -->
    <div class="alarm_form" v-if="alarm_form_status">
      <van-popup v-model="alarm_form_status">
        <van-form @submit="onSubmit">
          <input v-model="alarm_id" type="hidden"
                     name="alarm_id" rows=1 />
          <p>报警内容</p>
          <van-field v-model="alarm_contents"
                     name="alarm_content" rows="1"
                     autosize label="报警内容"
                     type="textarea" disabled></van-field>
          <van-field v-model="maintainer"
                     type="text" name="maintainer"
                     label="维保人" placeholder="请输入"
                     :rules="[{ required: true, message: '请填写维保人' }]"></van-field>
          <van-field v-model="maintenancecontent"
                     rows="1" name="maintenancecontent"
                     autosize label="维保内容"
                     type="textarea" placeholder="请输入"
                     :rules="[{ required: true, message: '请填写维保内容' }]"></van-field>
          <div class="buttom_alarm">
            <van-button round block type="info" native-type="submit" class="true_alarm" @click="closeform">
              取消
            </van-button>
            <van-button round block type="info" native-type="submit" class="true_alarm">
              确定
            </van-button>
          </div>
        </van-form>
      </van-popup>
    </div>

    <!-- 环形图表 -->
    <div class="circle">
      <div class="zhanwei1"></div>
      <van-circle class="circleGrid" v-model="onlineRate" :speed="100">
        <slot>
          <div class="line1">{{ onlineRateText }}%</div>
        </slot>
        <br/>
        <slot>
          <div class="line2">传感器在线率</div>
        </slot>
      </van-circle>
      <div class="zhanwei2"></div>
      <van-row>
        <van-col span="8">{{ totalAlarm }}</van-col>
        <van-col span="8">{{ onlinenum }}</van-col>
        <van-col span="8">{{ offlinenum }}</van-col>
      </van-row>
      <van-row>
        <van-col span="8" @click="btnClick_alarm">未处理报警数
        </van-col>
        <van-col span="8" @click="btnClick_onlineMonitor">在线传感器数</van-col>
        <van-col span="8">失联传感器</van-col>
      </van-row>
    </div>

    <!-- 告警列表组件 -->
    <van-cell title="报警详情" is-link icon="stop" value="更多" to="/alarm"/>
    <!--测试el-table-->
    <el-table
        :data="alarmList"
        :header-cell-style="{'text-align':'center'}"
        style="width:100vw"
        :cell-style="{'text-align':'center',padding:'0'}"
        :row-style="{height:'13vw'}">
      <el-table-column
          height="250"
          prop="createDate"
          label="报警时间"
          min-width="25%"
          min-height="30%">
      </el-table-column>
      <el-table-column
          size="small"
          prop="deviceName"
          label="传感器类型"
          min-width="25%">
      </el-table-column>
      <el-table-column
          prop="alarmLevel"
          label="告警等级"
          min-width="25%">
      </el-table-column>
      <el-table-column
          prop="handlestatus"
          label="处理状态"
          min-width="25%">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="primary"
              @click="handle(scope.$index)">
            未处理
          </el-button>
        </template>

      </el-table-column>
    </el-table>

    <van-cell>
      <template #icon>
        <span class="custom-title">机房信息</span>
      </template>
    </van-cell>
    <van-cell-group>
      <van-cell title="所属机构" :value="orgName"/>
      <van-cell title="机房编号" :value="roomCode"/>
      <van-cell title="机房名称" :value="roomName"/>
      <van-cell title="机房面积" :value="roomArea"/>
      <van-cell title="使用面积" :value="useArea"/>
      <van-cell title="建设年份" :value="buildDate"/>
      <van-cell title="负责人" :value="person"/>
      <van-cell title="机房位置" :value="machineaddress"/>
      <van-cell title="主机数量" :value="hostNum"/>
      <van-cell title="传感器数量" :value="deviceNum"/>
    </van-cell-group>

    <tabbar :active='0'></tabbar>
  </div>
</template>
<script>
import tabbar from "../comment/tabbar";

export default {
  components: {
    tabbar
  },
  data() {
    return {
      activeid: 0,
      activeid2: 0,
      activeIndex: 0,
      tableData: [],
      alarm_id: 0,
      //表单显示状态
      alarm_form_status: false,
      //报警内容
      alarm_content: {},
      //显示报警内容
      alarm_contents: '',
      //维保人
      maintainer: '',
      //维保内容
      maintenancecontent: '',
      currentid: '',
      currentwd: '请选择网点',
      alarmList: [],// 告警列表数据
      currentRate: 0,
      aaa: "",
      onlineRateText: '',
      onlineRate: 0,// 在线率
      totalAlarm: 0,// 未处理告警数
      onlinenum: 0,// 在线数量
      offlinenum: 0,// 离线数量
      show: false,
      orgName: '',
      roomCode: '',
      roomName: '',
      roomArea: '',
      useArea: '',
      buildDate: '',
      person: '',
      machineaddress: '',
      hostNum: '',
      deviceNum: '',
      active: 0,
      orgList: [],
      roomList: [],
      allorg: [],
      allroom: [],
      room: {},
      userId: ''
    };
  },
  computed: {
    text() {
      return this.currentRate.toFixed(0) + '%';
    },
  },
  beforeCreate() {//用于设置下行设备时清除定时器
    window.aaa = "";
  },
  beforeDestroy() {//页面关闭前清掉计时器
    clearInterval(this.timer);
  },
  methods: {
    /**
     * 布局组件跳转到不同页面
     * */
    btnClick_alarm() {
      const vm = this;
      vm.$router.push({name: 'alarm', params: { status: 0 }});
    },
    btnClick_onlineMonitor() {
      const vm = this;
      vm.$router.push({name: 'realtimemonitor'});
    },
    // 时间格式化
    dateFormat(fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")));
        }
      }
      return fmt;
    },
    /**
     * 点击二级列表，缓存选取值
     */
    onItemClick(text, id) {
      this.activeid2 = id + "";
      this.room = {"text": text, "id": id};
    },
    /**
     * 选择网点
     */
    onRoomSelect() {
      this.currentwd = this.room.text;
      this.currentid = this.room.id;
      localStorage.setItem("currentwd", JSON.stringify(this.room.text));
      localStorage.setItem("currentid", JSON.stringify(this.room.id));
      this.getInfo();
     /*this.getAlarmList();
      this.getOrgAndMachin();*/
      this.show = false;
    },
    /**
     * 切换一级
     */
    changeRoom(pid) {
      // roomList
      var roomArray = new Array();
      for (var i = 0; i < this.allroom.length; i++) {
        if (this.allroom[i].pid == pid) {
          roomArray.push(this.allroom[i]);
        }
      }
      this.roomList = roomArray;
    },
    /**
     * 选择第一级网点
     */
    onNavClick(index) {
      let pid = this.allorg[index].id;
      this.changeRoom(pid);
      this.activeid = index;
    },
    /**
     * 获取组织机构及机房
     */
    getOrgAndMachin() {
      this.$axios.post("/android/organizationTree", {
        userId: this.userId + ""
      }).then(res => {
        var allOrg = new Array();
        var allRoom = new Array();
        if (res.data.orgTree != null) {
          for (var i = 0; i < res.data.orgTree.length; i++) {
            if (res.data.orgTree[i].type == "org") {
              allOrg.push(res.data.orgTree[i]);
            } else {
              allRoom.push(res.data.orgTree[i]);
            }
          }
          this.allorg = allOrg;
          this.allroom = allRoom;
          this.orgList = allOrg;
          var roomArray = new Array();
          if (allOrg.length > 0) {
            for (var j = 0; j < this.allroom.length; j++) {
              if (this.allroom[j].pid == allOrg[0].id) {
                roomArray.push(this.allroom[j]);
              }
            }
            this.roomList = roomArray;
          }
        }
      });
    },
    toSelect() {
      this.show = true;
      this.currentwd = this.room.text;
      this.currentid = this.room.id;
      localStorage.setItem("currentwd", JSON.stringify(this.room.text));
      localStorage.setItem("currentid", JSON.stringify(this.room.id));
      this.getOrgAndMachin();
    },
    /**
     * 告警处理函数
     */
    handle(index) {
      // 赋值
      let alramObj = this.alarmList[index];
      this.alarm_contents = alramObj.createDate
          + alramObj.content;
      this.alarm_id = alramObj.id;
      this.alarm_form_status = true;
    },
    /**
     * 点击取消触发的事件
     */
    closeform() {
      this.alarm_form_status = false;
      this.clear();
    },
    //清空表单方法
    clear() {
      this.$data.maintainer = '';
      this.$data.maintenancecontent = '';
    },
    //保存方法
    onSubmit(values) {
      this.$axios.post('/android/alarmHanding', {
        alarmId: this.alarm_id + "",
        maintainer: values.maintainer,
        content: values.maintenancecontent
      }).then(function (e) {
        if (e.data.opertion == "操作成功") {
          self.$router.push('#/home');
        }
      });
      this.closeform();
      this.getAlarmList();
      alert("操作成功");
      this.clear();
    },
    getAlarmList() {
      if (this.currentid != "undefined" && this.currentid != "") {
        this.$axios.post("android/alarmManageState",
            {
              userId: this.userId + "",
              from: '1',
              size: '3',
              state: '0'
            },
        ).then(res => {
          this.alarmList = res.data.alarmList;
        });
      }
    },
    getInfo() {
      if (this.currentid != "undefined" && this.currentid != "") {
        this.$axios.post("/android/realTimeMonitor", {
          roomId: this.currentid + "",
          userId: this.userId + "",
          timestamp: this.dateFormat("YYYY-mm-dd HH:MM:SS", new Date())
        }).then(res => {
          let dataCollect = res.data;
          this.onlineRate = (dataCollect.total - dataCollect.offlineNum) / dataCollect.total * 100;
          this.onlineRateText = this.onlineRate.toFixed(1);
          this.totalAlarm = dataCollect.totalAlarm;
          this.onlinenum = dataCollect.total - dataCollect.offlineNum;
          this.offlinenum = dataCollect.offlineNum;
        });

        this.$axios.post("android/machineRoomDetail", {
          roomId: this.currentid + ""
        }).then(res => {
          let machineinfo = res.data.machineRoomVO;
          this.orgName = machineinfo.orgName;
          this.roomCode = machineinfo.roomCode;
          this.roomName = machineinfo.roomName;
          this.roomArea = machineinfo.roomArea;
          this.useArea = machineinfo.useArea;
          this.buildDate = machineinfo.buildDate;
          this.person = machineinfo.person;
          this.machineaddress = machineinfo.address;
          this.hostNum = machineinfo.hostNum;
          this.deviceNum = machineinfo.deviceNum;
        });
      }
    },
    /**
     * 获取页面初始化参数
     */
    getPageInfo() {
      var userObj = JSON.parse(localStorage.getItem("users"));
      this.userId = 1;
      if (userObj != null) {
        this.userId = userObj.id;
      }

      this.currentwd = localStorage.getItem("currentwd");
      this.currentid = localStorage.getItem("currentid");
      this.currentwd = this.currentwd.replace("\"", "");
      this.currentwd = this.currentwd.replace("\"", "");
      if (this.currentwd == "undefined") {
        this.currentwd = "请选择"
      }
    },
  },
  mounted() {
    this.getPageInfo();
    this.getInfo();
    this.getAlarmList();
    this.timer = setInterval(() => {
      this.getInfo();
      this.getAlarmList();
    }, 3000);
  }
};
</script>
<style>
.home {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  margin-top: 0px;
}

.title {
  width: 100vw;
  height: 11.733vw;
  background-color: #f2f2f2;
}

.nav-title {
  font-family: SourceHanSansCN-Regular;
  font-size: 4.8vw;
  font-weight: normal;
  font-stretch: normal;
  letter-spacing: 0vw;
  color: #333333;
  text-align: center;
  height: 11.733vw;
  line-height: 11.733vw;
}

.circle {
  text-align: center;
  background-color: #fff;
  padding-bottom: 3vw;
}

.circleGrid {
  width: 33.333vw;
  height: 33.333vw;
  background-color: #fff;
}

.zhanwei1 {
  width: 100vw;
  height: 10vw;
  background-color: #fff;
}

.zhanwei2 {
  width: 100vw;
  height: 5.5vw;
  background-color: #fff;
}

.van-nav-bar {
  background-color: #f2f2f2;
}

.van-field--disabled .van-field__label {
  color: #333;
}

.van-field__control:disabled {
  color: #333333;
  background-color: transparent;
  cursor: not-allowed;
  opacity: 1;
  -webkit-text-fill-color: currentColor;
}

.van-nav-bar__title {
  font-family: SourceHanSansCN-Regular;
  font-size: 4.8vw;

  font-weight: normal;
  font-stretch: normal;
  letter-spacing: 0vw;
  color: #333333;
}

.van-cell {
  font-family: SourceHanSansCN-Regular;
  font-size: 3.733vw;
  font-weight: normal;
  font-stretch: normal;
  letter-spacing: 0vw;
  color: #333333;
  line-height: 24px;
}

.van-nav-bar {
  background-color: rgb(247, 248, 250);
  height: 45px;
  width: 100%;
}

.line1 {
  font-family: SourceHanSansCN-Medium;
  font-size: 6vw;
  font-weight: normal;
  font-stretch: normal;
  letter-spacing: 0vw;
  color: #0195ff;
  margin-top: 5vw;
  position: relative;
}

.line2 {
  font-family: SourceHanSansCN-Regular;
  font-size: 3.2vw;
  font-weight: normal;
  font-stretch: normal;
  letter-spacing: 0vw;
  color: #666666;
  top: -3.333vw;
  position: relative;
}


#tab {
  width: 98%;
  margin: 0px auto;
}

#tab tr th {
  width: 50px;
  border: 0.133vw solid #c5cfd6;
  border-bottom-width: thin;
  border-right-style: none;
  border-left-style: none;
  border-top-style: none;


  font-family: SourceHanSansCN-Regular;
  font-size: 3.733vw;
  font-weight: normal;
  font-stretch: normal;
  line-height: 12vw;
  letter-spacing: 0vw;
  color: #666666;
}

.selectbtn {
  margin-left: 16vw;
  width: 60%;
  border-radius: 10px;
}
.active .van-cell__value--alone{
  color: #0195ff;
}
</style>
